package servlet.zyb;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class DoAddQuestionServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			addNewQuestion(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void addNewQuestion(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException, Exception {

		req.setCharacterEncoding("UTF-8");
		String questionname = (String) req.getParameter("qName");
		String questiontype = (String) req.getParameter("qType");
		System.out.println(questionname);
		System.out.println(questiontype);
		String[] options = req.getParameterValues("options");

		SAXBuilder builder = new SAXBuilder();

		Document document = builder.build(new File(
				"E:\\MyeclipseWorkspace\\vote\\question.xml"));

		Element root = document.getRootElement();

		Element question = new Element("question");

		Element qName = new Element("questionname").setText(questionname);
		Element qType = new Element("questiontype").setText(questiontype);
		Element qOptions = new Element("options");
		for (int i = 0; i < options.length; i++) {
			Element option = new Element("option").setText(options[i]);
			qOptions.addContent(option);
		}
		question.addContent(qName).addContent(qType).addContent(qOptions);
		root.addContent(question);

		XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
		FileOutputStream fos = new FileOutputStream(
				"E:\\MyeclipseWorkspace\\vote\\question.xml");
		out.output(document, fos);
		fos.close();

		resp.setContentType("text/html; charset=UTF-8");
		PrintWriter outs = resp.getWriter();
		outs.println("<HTML>");
		outs.println("  <HEAD><TITLE>success</TITLE></HEAD>");
		outs.println("  <BODY>");
		outs.print("添加成功");
		outs.println("  </BODY>");
		outs.println("</HTML>");
		outs.flush();
		outs.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			addNewQuestion(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
